package com.etymgiko.lyricshere.web.admin.song;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;

import javax.servlet.http.HttpServletRequest;

import com.etymgiko.lyricshere.manager.SongManager;
import com.etymgiko.lyricshere.model.Song;
import com.google.appengine.api.datastore.Text;

/**
 *
 * @author Ivan Holub
 */
public class EditSongFormController extends SimpleFormController {

    private SongManager songManager;

    public void setSongManager(SongManager songManager) {
        this.songManager = songManager;
    }

    protected ModelAndView onSubmit(Object o) throws Exception {

        SongCommand command = (SongCommand) o;

        Song song = new Song();
        song.setId(Long.valueOf(command.getId()));
        song.setTitle(command.getTitle());
        song.setCode(command.getCode());
        song.setLyrics(new Text(command.getLyrics()));
        songManager.updateSong(song);

        ModelAndView mav = new ModelAndView(getSuccessView() + "?id=" + song.getId());
        return mav;
    }

    @Override
    protected Object formBackingObject(HttpServletRequest httpServletRequest) throws Exception {
        String id = httpServletRequest.getParameter("id");
        Song song = songManager.getSong(Long.valueOf(id));
        SongCommand command = new SongCommand();
        command.setId(song.getId().toString());
        command.setTitle(song.getTitle());
        command.setCode(song.getCode());
        command.setLyrics(song.getLyrics().getValue());
        return command;
    }

    @Override
    protected void initBinder(HttpServletRequest httpServletRequest, ServletRequestDataBinder binder) throws Exception {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(false));
    }
}